package com.xzx.study.util;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.widget.ImageView;
import com.xzx.study.R;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

/**
 * @author xinzhixuan
 * @version V1.0
 * @date 2019/4/12 23:24
 */
public class ImageLoader {
    private Map<String, Bitmap> cacheMap = new HashMap<>();

    private Context context;

    public ImageLoader(Context context) {
        this.context = context;
    }

    public void loadImage(String imagePath, ImageView imageView) {
        imageView.setTag(imagePath);

        // 从一级缓存中是获取
        Bitmap bitmap = getFirstCache(imagePath);
        if (bitmap != null) {
            imageView.setImageBitmap(bitmap);
            return ;
        }

        bitmap = getSecondCache(imagePath);
        if (bitmap != null) {
            imageView.setImageBitmap(bitmap);
            cacheToFirstCache(imagePath, bitmap);
            return ;
        }

        loadThirdCache(imagePath, imageView);
    }

    private void cacheToSecondCache(String imagePath, Bitmap bitmap) {
        File externalFilesDir = context.getExternalFilesDir(null);
        String imageName = imagePath.substring(imagePath.lastIndexOf("/") + 1);
        assert externalFilesDir != null;
        File file = new File(externalFilesDir.getAbsolutePath() + "/" + imageName);
        try {
            FileOutputStream fileOutputStream = new FileOutputStream(file);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fileOutputStream);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }

    private void cacheToFirstCache(String imagePath, Bitmap bitmap) {
        cacheMap.put(imagePath, bitmap);
    }

    @SuppressLint("StaticFieldLeak")
    private void loadThirdCache(String imagePath, ImageView imageView) {
        new AsyncTask<Void, Void, Bitmap>() {
            @Override
            protected void onPreExecute() {
                imageView.setImageResource(R.drawable.loading);
            }

            @Override
            protected Bitmap doInBackground(Void... voids) {
                String tag = (String) imageView.getTag();
                if (!imagePath.equals(tag)) {
                    // 在加载前视图已经被复用了，不用加载了
                    return null;
                }

                try {
                    URL url = new URL(imagePath);
                    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                    connection.setConnectTimeout(5000);
                    connection.setReadTimeout(5000);
                    connection.connect();
                    InputStream inputStream = connection.getInputStream();
                    Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
                    inputStream.close();
                    connection.disconnect();
                    if (bitmap != null) {
                        cacheToFirstCache(imagePath, bitmap);
                        cacheToSecondCache(imagePath, bitmap);
                    }
                    return bitmap;
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return null;
            }

            @Override
            protected void onPostExecute(Bitmap bitmap) {
                if (bitmap != null ) {
                    String tag = (String) imageView.getTag();
                    if (!imagePath.equals(tag)) {
                        // 在加载前视图已经被复用了，不用显示了
                        return ;
                    }
                    imageView.setImageBitmap(bitmap);
                }
            }
        }.execute();
    }

    private Bitmap getSecondCache(String imagePath) {
        String absolutePath = context.getExternalFilesDir(null).getAbsolutePath();
        String imageName = imagePath.substring(imagePath.lastIndexOf("/") + 1);
        File file = new File(absolutePath + "/" + imageName);
        if (file.exists()) {
            return BitmapFactory.decodeFile(file.getAbsolutePath());
        }
        return null;
    }

    private Bitmap getFirstCache(String imagePath) {
        return cacheMap.get(imagePath);
    }
}
